package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 书名 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-03-13
 */
@RestController
@RequestMapping("/api/bookText")
public class BookTextController {

    @Autowired
    IBookTextService iBookTextService;

    @Autowired
    IBookTextSubjectsService iBookTextSubjectsService;

    @Autowired
    IBookTextYearClassService iBookTextYearClassService;

    @Autowired
    IBookOrderService iBookOrderService;

    @Autowired
    IBookTextDeadlineService iBookTextDeadlineService;

    @Autowired
    IQuarterService iQuarterService;

    @GetMapping()
    public Result findAll(@RequestParam(value = "name", defaultValue = "") String name) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(name), "name", name);
        wrapper.eq("status", 1);
        List<BookText> bookTextList = iBookTextService.list(wrapper);

        return new Result(Code.OK, bookTextList, "");
    }

    @GetMapping("/details")
    public Result findDetails(@RequestParam(value = "id", defaultValue = "") String id) {
        BookText bookText = iBookTextService.getById(id);

        if (bookText == null) {
            return new Result(Code.ERROR, null, "该教材不存在");
        }

//        String subjectsIdStr = iBookTextSubjectsService.getSubjectsIdByBookTextId(bookText.getId());
//        if (StringUtils.isNotBlank(subjectsIdStr)) {
//            bookText.setSubjectsIdStr(subjectsIdStr);
//        }

        BookText details = iBookTextService.getDistinctDetailsByBookTextId(bookText.getId());
        if (details != null) {
            bookText.setYearClassIdStr(details.getYearClassIdStr());
            bookText.setSubjectsIdStr(details.getSubjectsIdStr());
        }

        return new Result(Code.OK, bookText, Code.GET_OK_MSG);
    }

    @PostMapping("")
    public Result addOrUpdate(@RequestBody BookText bookText) {
        if (bookText.getId() != null) {
            BookText text = iBookTextService.getById(bookText.getId());

            if (text == null) {
                return new Result(Code.ERROR, null, "该教材不存在");
            }

            iBookTextService.updateById(bookText);

            // 清空科目表和年级表的数据，重新添加
//            iBookTextSubjectsService.remove(new QueryWrapper<BookTextSubjects>().eq("book_text_id", bookText.getId()));
            iBookTextYearClassService.remove(new QueryWrapper<BookTextYearClass>().eq("book_text_id", bookText.getId()));

        } else {
            iBookTextService.save(bookText);
        }

        if (StringUtils.isNotBlank(bookText.getSubjectsIdStr())) {
            // 根据逗号拆开
            String[] subjectsIdArr = bookText.getSubjectsIdStr().split(",");
            for (String subjectsId : subjectsIdArr) {
//                BookTextSubjects textSubjects = new BookTextSubjects();
//                textSubjects.setBookTextId(bookText.getId());
//                textSubjects.setSubjectsId(Long.valueOf(subjectsId));
//                iBookTextSubjectsService.save(textSubjects);

                if (StringUtils.isNotBlank(bookText.getYearClassIdStr())) {
                    // 根据逗号拆开
                    String[] yearClassIdArr = bookText.getYearClassIdStr().split(",");
                    for (String yearClassId : yearClassIdArr) {
                        BookTextYearClass textYearClass = new BookTextYearClass();
                        textYearClass.setSubjectsId(Long.valueOf(subjectsId));
                        textYearClass.setBookTextId(bookText.getId());
                        textYearClass.setYearClassId(Integer.valueOf(yearClassId));
                        iBookTextYearClassService.save(textYearClass);
                    }
                }
            }
        }

        Quarter quarter = iQuarterService.getNowQuarter();
        if (quarter != null) {
            BookTextDeadline bookTextDeadline = new BookTextDeadline();
            bookTextDeadline.setBookTextId(bookText.getId());
            bookTextDeadline.setStartQuarterId(Math.toIntExact(quarter.getId()));
            iBookTextDeadlineService.save(bookTextDeadline);
        }

        return new Result(Code.OK, null, Code.SAVE_OK_MSG);
    }

    @DeleteMapping("")
    public Result batchDel(@RequestParam(value = "idStr") String idStr) {
        String[] ids = idStr.split(",");

        // 判断是否有订购数据，如果已经有订购数据，无法删除
        StringBuilder messageSb = new StringBuilder();
        for (String id : ids) {
            BookText bookText = iBookTextService.getById(id);
            if (bookText == null) {
                return new Result(Code.ERROR, null, "该教材不存在");
            }

            Long count = iBookOrderService.count(new QueryWrapper<BookOrder>().eq("book_text_id", id));
            if (count > 0) {
                messageSb.append("“").append(bookText.getName()).append("”、");
            }
        }

        if (messageSb.length() > 0) {
            messageSb.deleteCharAt(messageSb.length() - 1);
            return new Result(Code.ERROR, null, messageSb.toString() + " 已有订购数据，无法删除");
        }

        for (String id : ids) {
            iBookTextService.removeById(id);
            iBookTextYearClassService.remove(new QueryWrapper<BookTextYearClass>().eq("book_text_id", id));
        }

        return new Result(Code.OK, "", Code.DELETE_OK_MSG);
    }

    @PostMapping("/setFrequent")
    public Result setFrequent(@RequestBody Map reMap) {
        Integer isFrequent = (Integer) reMap.get("isFrequent");// 是否设置为常用，0否1是
        List<String> idList = (List<String>) reMap.get("idList");

        for (String id : idList) {
            BookText bookText = iBookTextService.getById(id);
            if (bookText == null) {
                return new Result(Code.ERROR, null, "该教材不存在");
            }
            bookText.setIsFrequent(isFrequent);
            iBookTextService.updateById(bookText);
        }

        return new Result(Code.OK, null, Code.SAVE_OK_MSG);
    }

}
